package vn.lumi.smarthome.ui.base;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_Floor;
import vn.lumi.smarthome.io.database.TBL_Room;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.schedule.AddScheduleFragment;
import vn.lumi.smarthome.ui.setting.SettingFragment;
import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.CursorTreeAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class MenuFragment extends BaseFragmentMain implements
		LoaderCallbacks<Cursor> {
	public static final String TAG = "MenuFragment";
	public static final int GROUPEXPANDABLELIST_LOADER_ID = 0;
	// private boolean isGetDataDefault = true;

	private ExpandableListView mExpandableListView;
	private TextView mtxtTitle;
	private ImageButton mSetting;
	private MenuAdapter mMenuAdapter;
	private OnFloorRoomClickListener mOnFloorRoomClickListener;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mOnFloorRoomClickListener = (OnFloorRoomClickListener) activity;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Config.isVibrate = Preference.getVibrate(getActivity());
		changeLanguage();
	}

	public void changeLanguage() {
		Config.configLanguage(getActivity(),
				Preference.getLanguage(getActivity()));// Thiet lap ngon ngu
		mtxtTitle.setText(getString(R.string.txt_title_hello) + " " // Thiet lap
																	// lai ngon
																	// ngu vi
																	// mtxtTitle
																	// o trong
																	// ham
																	// onCreateView
				+ Preference.getUID(getActivity()));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_menu, container, false);
		init_view(view);
		init_loadData();
		return view;
	}

	private void init_view(View view) {
		mtxtTitle = (TextView) view.findViewById(R.id.fragment_menu_txt_title);
		mSetting = (ImageButton) view.findViewById(R.id.fragment_menu_setting);
		mSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();
				FragmentManager fragmentManager = getActivity()
						.getSupportFragmentManager();
				FragmentTransaction transaction = fragmentManager
						.beginTransaction();
				SettingFragment settingFragment = SettingFragment.newInstance(
						MainActivity.mRoomId, MainActivity.mFloorId,
						MainActivity.nameRoom, MainActivity.nameFloor);
				transaction.replace(R.id.activity_main_content,
						settingFragment,
						AddScheduleFragment.ADDSCHEDULEFRAGMENT);
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit,
						R.animator.fragment_slide_right_enter,
						R.animator.fragment_slide_right_exit);

				// Commit the transaction
				transaction.commit();
			}
		});
		mExpandableListView = (ExpandableListView) view
				.findViewById(R.id.fragment_menu_expand_listview);

		// Phai set mode de co the hightlight item khi bam vao item
		mExpandableListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
		mMenuAdapter = new MenuAdapter(null, getActivity());
		mExpandableListView.setAdapter(mMenuAdapter);
		mExpandableListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {

				if (Config.isVibrate)
					new VibrateThread(getActivity().getApplicationContext())
							.start();

				// Set state activated for item
				int index = parent.getFlatListPosition(ExpandableListView
						.getPackedPositionForChild(groupPosition, childPosition));
				parent.setItemChecked(index, true);
				Cursor groupCursor = mMenuAdapter.getGroup(groupPosition);
				Cursor childCursor = mMenuAdapter.getChild(groupPosition,
						childPosition);
				int groupId = groupCursor.getInt(groupCursor
						.getColumnIndex(TBL_Floor._ID));
				String groupName = groupCursor.getString(groupCursor
						.getColumnIndex(TBL_Floor.NAME));
				int childId = childCursor.getInt(childCursor
						.getColumnIndex(TBL_Room._ID));
				String childName = childCursor.getString(childCursor
						.getColumnIndex(TBL_Room.NAME));
				mOnFloorRoomClickListener.onFloorRoomClick(groupId, childId,
						groupName, childName);

				// Dong cursor
				if (groupCursor != null) {
					groupCursor = null;
				}
				if (childCursor != null) {
					childCursor = null;
				}
				return true;
			}
		});
		mExpandableListView
				.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

					@Override
					public boolean onGroupClick(ExpandableListView parent,
							View v, int groupPosition, long id) {
						// TODO Auto-generated method stub
						if (Config.isVibrate)
							new VibrateThread(getActivity()
									.getApplicationContext()).start();

						// Tra ve true de khong cho Expandable collapse
						return true;
					}
				});
		mtxtTitle.setText(getString(R.string.txt_title_hello) + " "
				+ Preference.getUID(getActivity()));
	}

	private void init_loadData() {
		getLoaderManager()
				.initLoader(GROUPEXPANDABLELIST_LOADER_ID, null, this);
	}

	/**
	 * Interface for item in menu is clicked
	 * 
	 * @author TUNGDX
	 * 
	 */
	public interface OnFloorRoomClickListener {
		/**
		 * Event when click
		 * 
		 * @param floor_id
		 *            id of floor which is clicked
		 * @param room_id
		 *            id of room which is clicked
		 */
		public void onFloorRoomClick(int floor_id, int room_id,
				String floor_name, String room_name);
	}

	private static class MenuAdapter extends CursorTreeAdapter {
		private Context mContext;

		// private Cursor groupCursor = null;
		public MenuAdapter(Cursor cursor, Context context) {
			super(cursor, context);
			mContext = context;
			// groupCursor = cursor;
		}

		@Override
		protected void bindChildView(View view, Context context, Cursor cursor,
				boolean isLastChild) {
			TextView textView = (TextView) view
					.findViewById(R.id.item_expandablelistview_item_txt);
			textView.setText(cursor.getString(cursor
					.getColumnIndex(TBL_Room.NAME)));
		}

		@Override
		protected void bindGroupView(View view, Context context, Cursor cursor,
				boolean isExpanded) {
			if (getGroupCount() == 1) {
				view.setVisibility(View.INVISIBLE);
			} else {
				view.setBackgroundDrawable(view.getResources().getDrawable(
						R.color.greenActionbar));
				TextView textView = (TextView) view
						.findViewById(R.id.item_expandablelistview_groupview_txt);
				textView.setText(cursor.getString(cursor
						.getColumnIndex(TBL_Floor.NAME)));
			}

		}

		@Override
		protected Cursor getChildrenCursor(Cursor groupCursor) {
			int index = groupCursor.getColumnIndex(TBL_Floor._ID);
			int floor_id = groupCursor.getInt(index);
			String selection = TBL_Room.FLOOR_ID + "=?";
			String[] where = new String[] { floor_id + "" };
			CursorLoader cursorLoader = new CursorLoader(mContext,
					TBL_Room.CONTENT_URI_ROOM, null, selection, where, null);
			Cursor childCursor = null;
			try {
				childCursor = cursorLoader.loadInBackground();
				Log.d(TAG, "childCursor " + childCursor.getCount());
				childCursor.moveToFirst();
			} catch (Exception e) {
				Log.e(TAG, e.getMessage());
			}

			return childCursor;
		}

		@Override
		protected View newChildView(Context context, Cursor cursor,
				boolean isLastChild, ViewGroup parent) {
			return View.inflate(context, R.layout.item_expandablelistview_item,
					null);
		}

		@Override
		protected View newGroupView(Context context, Cursor cursor,
				boolean isExpanded, ViewGroup parent) {

			View view = View.inflate(context,
					R.layout.item_expandablelistview_groupview, null);
			return view;
		}

	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		return new CursorLoader(getActivity(), TBL_Floor.CONTENT_URI_FLOOR,
				null, null, null, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		LogUltis.i(TAG, "Load MenuFragment finish, rows=" + cursor.getCount());

		// Hieuph modify
		// Swap the new cursor in.
		int id = loader.getId();
		if (id == GROUPEXPANDABLELIST_LOADER_ID) {
			mMenuAdapter.setGroupCursor(cursor);
			// end

			// Mo rong expandlist o cacvi tri group
			for (int i = 0; i < mMenuAdapter.getGroupCount(); i++) {
				mExpandableListView.expandGroup(i);
			}

			// Set select cho item so 1.
			// Chu y phai doi voi expand ListView thi phai expandGroup moi co the su dung duoc dong
			// nay
			mExpandableListView.setItemChecked(1, true);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {

		// hieuph1 modify
		int id = loader.getId();
		if (id != GROUPEXPANDABLELIST_LOADER_ID) {
			// child cursor
			try {
				mMenuAdapter.setChildrenCursor(id, null);
			} catch (NullPointerException e) {
				Log.w("TAG", "Adapter expired, try again on the next query: "
						+ e.getMessage());
			}
		} else {
			mMenuAdapter.setGroupCursor(null);
		}
		// end
	}

	@Override
	public void refreshData(int floor_id, int room_id, String nameRoom,
			String nameFloor) {
		// TODO Auto-generated method stub

	}

}
